<?php

namespace app\site\controller\open;

use app\service\Captcha\AjCaptchaService;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class CaptchaController
{

    /**
     * 生成验证码
     * @throws \Exception
     */
    public function get(Request $request, AjCaptchaService $ajCaptchaService): \think\response\Json
    {
        $captchaType = $request->param('captchaType');

        if (!in_array($captchaType, ['blockPuzzle','clickWord'])){
            $this->error('验证方式错误');
        }
        $captcha = $ajCaptchaService->create($captchaType);
        $this->success($captcha);

    }

    /**
     * 第一次验证
     * @param Request $request
     * @param AjCaptchaService $ajCaptchaService
     * @return void
     */
    public function check(Request $request, AjCaptchaService $ajCaptchaService){
        $data = $request->param();
        $captchaType = $data['captchaType']??'';
        if (!in_array($captchaType, ['blockPuzzle','clickWord'])){
            $this->error("验证方式错误");
        }
        try {
            $ajCaptchaService->check($data);
        }catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        $this->success($data);
    }


    protected function success($data=null)
    {
        $response = [
            'error' => false,
            'repCode' => '0000',
            'repData' => $data,
            'repMsg' => null,
            'success' => true,
        ];
        throw new HttpResponseException(Response::create($response, 'json'));
    }


    protected function error($msg)
    {
        $response = [
            'error' => true,
            'repCode' => '6111',
            'repData' => null,
            'repMsg' => $msg,
            'success' => false,
        ];
        throw new HttpResponseException(Response::create($response, 'json'));
    }


}
